package com.github.niefy.modules.wxma.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.hutool.core.util.StrUtil;
import com.github.niefy.common.utils.R;
import com.github.niefy.modules.sys.service.SysLogService;
import com.github.niefy.modules.wxma.dto.WxMaCheckBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 微信网页授权相关
 */
@RestController
@RequestMapping("/maAuth")
@Api(tags = {"微信小程序授权"})
@RequiredArgsConstructor
public class MaAuthController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SysLogService sysLogService;

    private final WxMaService wxMaService;

    /**
     * 登陆接口
     */
    @ApiOperation(value = "患者微信小程序JSCODE", httpMethod = "GET")
    @GetMapping("/getMpJscode")
    public R getMpJscode(String appid, String code) {
        if (StrUtil.isBlank(code)) {
            return R.error("empty jscode");
        }
        try {
            this.wxMaService.switchoverTo(appid);
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            return R.ok().put(session);
        } catch (WxErrorException e) {
            logger.error(e.getMessage(), e);
            return R.error(e.toString());
        }
    }


    /**
     * 小程序注册
     */
    @ApiOperation(value = "获取微信小程序用户基本信息", httpMethod = "POST")
    @PostMapping("/getMpUserInfoOrPhone")
    public R getMpUserInfoOrPhone(@RequestBody WxMaCheckBo wxMaCheckBo) {
        if (StrUtil.isEmpty(wxMaCheckBo.getType())) {
            return R.error("type is empty");
        }
        this.wxMaService.switchoverTo(wxMaCheckBo.getAppid());
        if ("user".equals(wxMaCheckBo.getType())) {
            // 用户信息校验
            if (!wxMaService.getUserService().checkUserInfo(wxMaCheckBo.getSessionKey(), wxMaCheckBo.getRawData(), wxMaCheckBo.getSignature())) {
                return R.error("user check failed");
            }

            // 解密用户信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(wxMaCheckBo.getSessionKey(), wxMaCheckBo.getEncryptedData(), wxMaCheckBo.getIv());
            return R.ok().put(userInfo);
        }
        if ("phone".equals(wxMaCheckBo.getType())) {
            // 解密手机号
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(wxMaCheckBo.getSessionKey(), wxMaCheckBo.getEncryptedData(), wxMaCheckBo.getIv());
            return R.ok().put(phoneNoInfo);
        }
        return R.error();

    }


    @ApiOperation(value = "患者微信小程序AccessToken", httpMethod = "GET")
    @GetMapping("/getAccessToken")
    public R getMaAccessToken(String appid) throws WxErrorException {
        if (StrUtil.isBlank(appid)) {
            return R.error("empty appid");
        }
        this.wxMaService.switchoverTo(appid);
        WxAccessToken wxAccessToken = new WxAccessToken();
        WxMaConfig config = wxMaService.getWxMaConfig();
        if (config.getExpiresTime() < 10) {
            this.wxMaService.getAccessToken(true);
        }
        wxAccessToken.setAccessToken(config.getAccessToken());
        wxAccessToken.setExpiresIn((int) config.getExpiresTime());
        return R.ok().put(wxAccessToken);

    }

}
